<?php

namespace app\api\controller\integral;

use app\common\controller\Api;
use think\Db;

//积分商城
class Integral extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 我的积分
     * @ApiMethod (GET)
     * @path api/integral/integral/index
     */
    public function index()
    {
        $userId = $this->auth->id;
        $page = $this->request->param('page',1);
        $integral = db('user')->where('id',$userId)->value('integral');
        $useIntegral = db('integral_change_log')->where(['user_id'=>$userId,'type'=>'1','user_del'=>'0'])->sum('score');//已使用积分
        $log = db('integral_change_log')
            ->where('user_id',$userId)
            ->where('user_del','0')
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $backList = [
            'integral'=>$integral,
            'use_integral'=>$useIntegral,
            'list'=>$log->toArray()
        ];
        $this->success('操作成功',$backList);
    }


    /**
     * 积分产品列表
     * @ApiMethod (GET)
     * @path api/integral/integral/goodslist
     */
    public function goodslist()
    {
        $userId = $this->auth->id;
        $page = $this->request->param('page',1);
        $integral = db('user')->where('id',$userId)->value('integral');

        $log = db('integral_goods')
            ->where('is_on_sale',1)
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        $log = $log->toArray();
        $log['data'] = addWebSiteUrl($log['data'],['image','goods_images']);
        $banner = db('integral_banner')->field('id,name,image')->where('status',1)->where('type',1)->select();
        $banner = addWebSiteUrl($banner,['image']);
        $backList = [
            'integral'=>$integral,
            'banner'=>$banner,
            'list'=>$log
        ];
        $this->success('操作成功',$backList);
    }

    /**
     * 积分产品详情
     * @ApiMethod (GET)
     * @path api/integral/integral/goodsDetail
     */
    public function goodsDetail()
    {
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $goodsId = $this->request->param('goods_id',0);//产品ID
        $goods = db('integral_goods')->where('id',$goodsId)->find();
        if (empty($goods)) {
            $this->error('产品不存在');
        }

        $store = db('store')->where('id',$storeId)->find();
        $goods['store_name'] = $store['store_name'];
        $goods['store_image'] = $store['avatar'];
        $goods = addWebSiteUrl($goods,['image','store_image']);
        $goodsImages = explode(',',$goods['goods_images']);
        $goodsImagesArr = [];
        foreach ($goodsImages as $key => $value) {
            $goodsImagesArr[] = addWebSiteUrl(['goods_images'=>$value],['goods_images']);
        }
        $goods['goods_images'] = $goodsImagesArr;
        $goods['content'] = get_image_url($goods['content'],protocol_name() . '://' . $_SERVER['SERVER_NAME']);
        $goods['cashsale'] = $goods['cashsale']+$goods['salecount'];

        $backList = [
            'list'=>$goods
        ];
        $this->success('操作成功',$backList);
    }

    /**
     * 积分产品结算页
     * @ApiMethod (GET)
     * @path api/integral/integral/goodsSettlement
     */
    public function goodsSettlement()
    {
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $userId = $this->auth->id;

        $goodsId = $this->request->param('goods_id',0);//产品ID

        $address = db('address')->field('id,name,tel')->where('is_default','1')->where('user_id',$userId)->find();

        $store = db('store')->field('store_name,tel,avatar,kefu_qrcode,business_start_time,business_end_time,province,city,area,address')->where('id',$storeId)->find();
        $store = addWebSiteUrl($store,['avatar']);
        $province = db('area')->where('id',$store['province'])->value('name');
        $city = db('area')->where('id',$store['city'])->value('name');
        $area = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province;
        $store['city_name'] = $city;
        $store['area_name'] = $area;
        $goods = db('integral_goods')->where('id',$goodsId)->find();
        $goods = addWebSiteUrl($goods,['image','goods_images']);
        $backList = [
            'store'=>$store,
            'address'=>$address,
            'goods'=>$goods
        ];
        $this->success('操作成功',$backList);
    }

    /**
     * 创建积分订单
     * @ApiMethod (POST)
     * @path api/integral/integral/createOrder
     */
    public function createOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
            $goodsId = $this->request->param('goods_id',0);//产品ID
            $addressId = $this->request->param('address_id',0);//地址ID
            $today = date('Y-m-d H:i:s');
            $todayEnd = date('Y-m-d H:i:s',strtotime(date('Y-m-d'))+86400);
            $startDate = date('Y-m-01 00:00:00'); // 获取本月开始时间
            $endDate = date('Y-m-t 23:59:59');// 获取本月结束时间

            $thisToday = date('Y-m-d H:i:s',time());

            $goods = db('integral_goods')->where('id',$goodsId)->find();
            if ($goods['is_on_sale'] < 1) {
                Db::rollback();
                $this->error('产品已下架');
            }
            if ($goods['stock'] < 1) {
                Db::rollback();
                $this->error('库存不足');
            }
            $integral = db('user')->where('id',$userId)->value('integral');

            //今日花费积分
            $daySpendIntegral = db('integral_change_log')
                ->where(['user_id'=>$userId,'type'=>'1','user_del'=>'0'])
                ->where("addtime >='{$today}' AND addtime < '{$todayEnd}'")
                ->sum('score');

            //本月花费积分
            $monthSpendIntegral = db('integral_change_log')
                ->where(['user_id'=>$userId,'type'=>'1','user_del'=>'0'])
                ->where("addtime >='{$startDate}' AND addtime <= '{$endDate}'")
                ->sum('score');

            $dayLimit = db('integral_score_rule')->where('type',6)->find();//日上限制
            $monthLimit = db('integral_score_rule')->where('type',7)->find();//月上限制
            $scoreLimit = db('integral_score_rule')->where('type',5)->find();//积分过期时长

            $sumIntegral = db('integral_change_log')
                ->where(['type'=>2,'user_id'=>$userId,'status'=>0])
                ->where("exptime > '{$thisToday}'")
                ->sum('residue_score');

            if ($integral < $goods['price'] || $sumIntegral < $goods['price']) {
                Db::rollback();
                $this->error('积分不足');
            }
            if ($dayLimit['cost_day'] < $daySpendIntegral+$goods['price']) {
                Db::rollback();
                $this->error('积分花费已经达到日上限');
            }
            if ($monthLimit['cost_month'] < $monthSpendIntegral+$goods['price']) {
                Db::rollback();
                $this->error('积分花费已经达到月上限');
            }

            $address = db('address')->where('id',$addressId)->find();
            $province = db('area')->where('id',$address['province'])->value('name');
            $city = db('area')->where('id',$address['city'])->value('name');
            $area = db('area')->where('id',$address['area'])->value('name');



            $orderId = db('integral_order')->insertGetId([
                'order_no'=>generateOrderNumber(),
                'user_id'=>$userId,
                'username'=>$address['name'],
                'store_id'=>$storeId,
                'tel'=>$address['tel'],
                'price'=>$goods['price'],
                'order_status'=>1,
                'addtime'=>time(),
                'pay_time'=>time(),
                'code'=>generateUniqueCode(4,$storeId),
                'address'=>$province.$city.$area.$address['address'],
            ]);

            db('integral_order_goods')->insert([
                'order_id'=>$orderId,
                'goods_id'=>$goodsId,
                'goods_name'=>$goods['goods_name'],
                'cost_price'=>$goods['cost_price'],
                'order_price'=>$goods['price'],
                'num'=>1,
                'spec_name'=>$goods['spec_name'],
                'goods_pic'=>$goods['image'],
                'addtime'=>time()
            ]);

            //减库存
            db('integral_goods')->where('id',$goodsId)->lock(true)->find();
            db('integral_goods')->where('id',$goodsId)->setDec('stock',1);
            /*******************************积分操作Start********************************/
            //从可用积分中，扣除使用的积分
            $changeLog = db('integral_change_log')
                ->where(['type'=>2,'user_id'=>$userId,'status'=>0])
                ->where('residue_score','>',0)
                ->where("exptime > '{$thisToday}'")
                ->order('addtime ASC')
                ->select();

            //更新可用积分记录
            $integralThis = $goods['price'];
            foreach ($changeLog AS $key => $value) {
                $residueScore = $value['residue_score'];
                if ($residueScore < $integralThis) {
                    db('integral_change_log')->where('id',$value['id'])->update(['residue_score'=>0]);
                    $integralThis-=$residueScore;
                } else {
                    db('integral_change_log')->where('id',$value['id'])->setDec('residue_score',$integralThis);
                    break;
                }
            }

            //扣除积分
            $uuser = db('user')->where('id',$userId)->lock(true)->find();
            db('user')->where('id',$userId)->setDec('integral',$goods['price']);
            $integral = $uuser['integral'];
            //增加积分变动日志
            db('integral_change_log')->insert([
                'user_id'=>$userId,
                'store_id'=>$storeId,
                'scene'=>5,
                'score'=>$goods['price'],
                'total_score'=>bcsub($integral,$goods['price'],2),
                'type'=>1,
                'order_id'=>$orderId,
                'addtime'=>date('Y-m-d H:i:s',time())
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        /*******************************积分操作End********************************/
        $this->success('兑换成功',[
            'order_id'=>$orderId
        ]);
    }

    /**
     * 订单列表
     * @path api/integral/integral/orderList
     */
    public function orderList()
    {
        $userId = $this->auth->id;//后期从token或者公共存储区域读取
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $where = ['user_id'=>$userId,'store_id'=>$storeId];
        $page = $this->request->param('page',1);
        $orderStatus = $this->request->param('order_status',1);
        if (!empty($orderStatus)) {
            $where['order_status'] = $orderStatus;
        }
        $order = db('integral_order')
            ->where($where)
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        if (!empty($order)) {
            $order = $order->toArray();

            foreach ($order['data'] AS $key => $value) {

                $orderGoods = db('integral_order_goods')->where('order_id',$value['id'])->select();
                $orderGoods = addWebSiteUrl($orderGoods,['goods_pic']);
                $order['data'][$key]['order_goods'] = $orderGoods;
            }
        }
        $this->success('请求成功',$order);
    }

    /**
     * 订单详情
     * @path api/integral/integral/orderDetail
     */
    public function orderDetail()
    {
        $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
        $orderId = $this->request->param('order_id',0);
        $orderInfo = db('integral_order')->where('id',$orderId)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }

        $orderInfo['addtime'] = date('Y-m-d H:i:s',$orderInfo['addtime']);
        $orderInfo['pay_time'] = date('Y-m-d H:i:s',$orderInfo['pay_time']);
        $orderInfo['order_qr_time'] = date('Y-m-d H:i:s',$orderInfo['order_qr_time']);
        $orderInfo['qx_time'] = date('Y-m-d H:i:s',$orderInfo['qx_time']);
        $orderInfo['delivery_time'] = date('Y-m-d H:i:s',$orderInfo['delivery_time']);


        $orderGoods = db('integral_order_goods')->where('order_id',$orderId)->find();
        $orderGoods = addWebSiteUrl($orderGoods,['goods_pic']);
        $orderInfo['order_goods'] = $orderGoods;
        $store = db('store')->field('store_name,tel,avatar,kefu_qrcode,business_start_time,business_end_time,province,city,area,address')->where('id',$storeId)->find();
        $store = addWebSiteUrl($store,['avatar']);
        $province = db('area')->where('id',$store['province'])->value('name');
        $city = db('area')->where('id',$store['city'])->value('name');
        $area = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province;
        $store['city_name'] = $city;
        $store['area_name'] = $area;
        $this->success('请求成功',[
            'order'=>$orderInfo,
            'store'=>$store
        ]);
    }

    /**
     * 订单核销码
     * @path api/integral/integral/orderCode
     */
    public function orderCode()
    {
        $orderId = $this->request->param('order_id',0);
        $orderInfo = db('integral_order')->field('id,code')->where('id',$orderId)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }
        $this->success('请求成功',$orderInfo);
    }

    /**
     * 每日签到
     * @path api/integral/integral/dailyCheckin
     */
    public function dailyCheckin()
    {
        $userId = $this->auth->id;
        $storeId = $this->auth->store_id;
        $today = date('Y-m-d');
        $log = db('sign_log')->where(['day'=>$today,'user_id'=>$userId])->find();
        $gDay = db('integral_score_rule')->where('type',5)->value('day');
        $guoQi = strtotime(date('Y-m-d'))+86400+$gDay*86400;

        if (!empty($log)) {
            $this->error('一天只能签到一次');
        }
        Db::startTrans();
        try{
            $score = db('integral_score_rule')->where('type',3)->value('score');
            db('sign_log')->insert([
                'user_id'=>$userId,
                'day'=>$today,
                'score'=>$score,
                'addtime'=>time()
            ]);
            $user = db('user')->where('id',$userId)->lock(true)->find();
            db('user')->where('id',$userId)->setInc('integral',$score);
            
            db('integral_change_log')->insert([
                'user_id'=>$userId,
                'store_id'=>$storeId,
                'scene'=>3,
                'score'=>$score,
                'total_score'=>bcadd($user['integral'],$score,2),
                'residue_score'=>$score,
                'type'=>2,
                'exptime'=>date('Y-m-d H:i:s',$guoQi),
                'addtime'=>date('Y-m-d H:i:s'),
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('签到成功',['score'=>$score]);
    }

    /**
     * 确认收货
     * @path api/integral/integral/confirmOrder
     */
    public function confirmOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;//后期从token或者公共存储区域读取
            $orderId = $this->request->post('order_id', 0);
            $store = db('store')->where('id', $storeId)->find();
            $orderInfo = db('integral_order')->where(['user_id' => $userId, 'id' => $orderId])->find();
            if (empty($orderInfo)) {
                Db::rollback();
                $this->error('订单不存在');
            }
            if ($orderInfo['order_status'] == 2) {
                Db::rollback();
                $this->error('订单状态错误');
            }
            /**********更新订单状态**********/
            db('integral_order')->where(['user_id' => $userId, 'id' => $orderId])->update([
                'order_status' => 2,
                'order_qr_time' => time()
            ]);

            $orderGoods = db('integral_order_goods')->where(['order_id' => $orderId])->select();
            foreach ($orderGoods AS $key => $value) {
                //更新商品销量
                db('integral_goods')->where('id',$value['goods_id'])->setInc('salecount',$value['num']);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('已确认收货');
    }


    /**
     * 签到页面接口
     * @path api/integral/integral/signData
     */
    public function signData()
    {
        $times = $this->get_week(time());
        $userId = $this->auth->id;
        $score = db('integral_score_rule')->where('type',3)->value('score');
        $today = date('Y-m-d');
        $log = db('sign_log')->where(['day'=>$today,'user_id'=>$userId])->find();
        $isQianDao = false;
        if (!empty($log)) {
            $isQianDao = true;
        }
        $this->success('请求成功',[
            'times'=>$times,
            'score'=>$score,
            'is_qian'=>$isQianDao
        ]);
    }

    /**
    * @param time 要获取的日期（此处为时间戳） 
    * @param format 要返回的日期格式
    * @return array 当前周数组
    */
    public function get_week($time = '', $format='m.d'){
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $date = [];
        if(empty($week)){
            $week = 7;
        }
        for ($i=0; $i< 7; $i++){
            $checked = false;
            if (date('Y-m-d',strtotime( '+' . ($i+1-$week) .' days', $time)) == date('Y-m-d',$time)) {
                $checked = true;
            }
            $date[$i] = [
                'date'=>date($format ,strtotime( '+' . ($i+1-$week) .' days', $time)),
                'checked'=>$checked
            ];
        }
        return $date;
    }

}
